﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace SkypeBot.Commands
{
    using SkypeBot.Core;

    class Commands : IResult
    {
        private CommandExecutor CommandExecutor;
        public Commands()
        {
            CommandExecutor = new CommandExecutor();
            var handlers = GetHandlers(Assembly.Load("Commands")).Select(CreateInstance).Where(h => h != null).ToList();
            handlers.ForEach(x => CommandExecutor.RegisterMessageHandler(x));
        }

        public Responce GetResult(Message message)
        {
            return CommandExecutor.ExecuteCommand(message);
        }

        private static IEnumerable<Type> GetHandlers(Assembly assembly)
        {
            return assembly.GetTypes().Where(t => typeof(IMessageHandler).IsAssignableFrom(t));
        }

        private static IMessageHandler CreateInstance(Type handlerType)
        {
            var construstor = handlerType.GetConstructor(Type.EmptyTypes);

            if (construstor != null)
            {
                return Activator.CreateInstance(handlerType) as IMessageHandler;
            }

            return null;
        }
    }
}
